package com.onpositive.knowledge.model.values;

import java.util.ArrayList;

import com.onpositive.semantic.model.api.meta.BaseMeta;
import com.onpositive.semantic.model.api.meta.DefaultMetaKeys;
import com.onpositive.semantic.model.api.meta.IMeta;
import com.onpositive.semantic.model.api.property.IProperty;
import com.onpositive.semantic.model.api.property.ValueUtils;

public class ToSingleValue implements IProperty {

	final IProperty prop;
	final BaseMeta meta;

	public ToSingleValue(IProperty prop) {
		super();
		this.prop = prop;
		this.meta = new BaseMeta(prop.getMeta());
		this.meta.putMeta(DefaultMetaKeys.MULTI_VALUE_KEY, false);
	}

	@Override
	public IMeta getMeta() {
		return meta;
	}

	@Override
	public String getId() {
		return prop.getId();
	}

	@Override
	public Object getValue(Object obj) {
		Object value = prop.getValue(obj);
		Iterable<Object> collection = ValueUtils.toCollection(value);
		if (collection != null) {
			ArrayList<DescribedValue> ds = new ArrayList<DescribedValue>();
			for (Object o : collection) {
				if (!(o instanceof DescribedValue)) {
					ds.add(new DescribedValue(o, null));
				} else {
					ds.add((DescribedValue) o);
				}
			}
			return DescribedValue.chooseBest(ds);
		}
		return null;
	}

}
